import {ScrollView, Text, View} from "@tarojs/components";
import React, {useCallback, useEffect, useRef, useState} from "react";
import {getOrderStatusStyle, OrderStatus, OrderStatusInfoType} from "@/common/enums";
import {ActionSheet, Button, Cell, CellGroup, Empty, Icon, Image} from "@antmjs/vantui";
import DateUtils from "@/utils/date_utils";
import BottomButton from "@/components/bottom_button";
import Utils from "@/utils/common";
import RouthPath from "@/common/RouthPath";
import {BalanceModel, CouponsModel, IdParams, InvoiceParams, OrderItem, OrderParams} from "@/common/apis/model";
import {
  balancePayApi,
  getPayParamsApi,
  orderCancelApi,
  orderInfoApi,
  userBalanceApi
} from "@/common/apis/home_datasource";
import ShowUtils from "@/utils/show_utils";
import LocalData from "@/common/local_data";
import EventUtils from "@/utils/event_utils";
import Taro from "@tarojs/taro";
import NumberUtils from "@/utils/number_utils";
import KefuDialog from "@/components/kefu_dialog";
import AssetImage from "@/common/AssetImage";
import './order_detail.less'
import LogUtils from "@/utils/log";


definePageConfig({
  navigationBarTitleText: '预约详情'
})
export default function Order_detail() {
  const statusStyle = useRef<OrderStatusInfoType>();
  const orderInfo = useRef<OrderItem>();
  const coupon = useRef<CouponsModel | null>(null);
  const idParams = useRef<OrderParams>();
  const balanceModel = useRef<BalanceModel>();
  const channelEvent = useRef<Taro.EventChannel | null>();
  const options = useRef([
    {name: '个人余额支付', value: '0', disabled: false},
    {name: '微信支付', value: '2', disabled: false},
  ]);

  const handlePayStyleSelect = (e: any) => {
    const value = e.detail.value;
    setShow(false)
    Utils.modal("提示", `确定要支付${getPayMoney()}吗？`, true, (ok) => {
      if (ok) {
        if (value === '2') {
          //微信支付
          getPayParamsApi(orderInfo.current?.id).then((payParams) => {
            if (payParams) {
              if (payParams) {
                Utils.payWx(payParams, (res) => {
                  Utils.emit(channelEvent.current, EventUtils.RefreshOrder, true)
                  Utils.showOkToast('支付成功')
                  Utils.navigateBack()
                })
              }
            }
          })
        } else {
          //余额支付
          balancePayApi(orderInfo.current?.id, value).then((res) => {
            if (res) {
              Utils.emit(channelEvent.current, EventUtils.RefreshOrder, true)
              Utils.showOkToast('支付成功')
              Utils.navigateBack()
            }
          })
        }
      }
    })
  }
  const kefuDialogRef = useRef(null);
  const openDialog = () => {
    // 通过 ref 调用子组件的 setShow 方法
    if (kefuDialogRef.current) {
      kefuDialogRef.current.setShow(true);
    }
  };

  const getPayMoney = useCallback(() => {
    const amount2 = NumberUtils.stringToNumber(orderInfo.current?.actualAmount)
    //如果有优惠券，就减去
    if (coupon.current) {
      const amount1 = NumberUtils.stringToNumber(coupon.current?.discount)
      return amount2 - amount1
    } else {
      return amount2
    }
  }, []);


  const setOptions = useCallback(() => {
    ///应支付金额
    const amount2 = getPayMoney()
    ///用户的余额
    const b1 = NumberUtils.stringToNumber(balanceModel.current?.user)
    const userBalance = ShowUtils.getDefaultPrice(balanceModel.current?.user)
    //用户余额是否满足支付
    const disable1 = b1 < amount2
    if (ShowUtils.isValidTeamId(orderInfo.current?.teamId)) {
      const teamBalance = ShowUtils.getDefaultPrice(balanceModel.current?.team)
      //团队的余额
      const b2 = NumberUtils.stringToNumber(balanceModel.current?.team)
      const disable2 = b2 < amount2
      options.current = [
        {name: `个人余额(${userBalance})`, value: '0', disabled: disable1},
        {name: `团队余额(${teamBalance})`, value: '1', disabled: disable2},
        {name: '微信', value: '2', disabled: false},
      ]
      //判断余额不足
    } else {
      options.current = [
        {name: `个人余额(${userBalance})`, value: '0', disabled: disable1},
        {name: '微信', value: '2', disabled: false},
      ]
    }
  }, [getPayMoney]);


  const getUserBalance = useCallback(() => {
    const teamId = ShowUtils.isValidTeamId(orderInfo.current?.teamId)
    if (teamId) {
      userBalanceApi(orderInfo.current?.teamId).then((res) => {
        if (res) {
          balanceModel.current = res;
          setOptions()
        }
      })
    } else {
      userBalanceApi().then((res) => {
        if (res) {
          balanceModel.current = res;
          setOptions()
        }
      })
    }
  }, [setOptions]);

  const getOrderInfo = useCallback(() => {
    if (idParams.current && idParams.current?.id) {
      orderInfoApi(idParams.current?.id).then((res) => {
        if (res) {
          orderInfo.current = res;
          getUserBalance()
          statusStyle.current = getOrderStatusStyle(res.status)
          setRefresh({})
        }
      })
    }
  }, [getUserBalance]);

  const [, setRefresh] = useState({})
  useEffect(() => {
    const i = Utils.getI()
    const params = Utils.getParamsByRouter(i)
    channelEvent.current = Utils.getChannel(i)
    if (params && params.data) {
      idParams.current = Utils.getObjectWithUrl<IdParams>(params.data)
      getOrderInfo();
    }
  }, [getOrderInfo]);

  const handleButtons = useCallback((type) => {
    if (orderInfo.current) {
      if (type === 0) {
        setShow(true)
      } else if (type === 1) {
        const url = Utils.getUrlWithObject(RouthPath.confirmBook, orderInfo.current)
        Utils.navigateAndListenToEvent(url, EventUtils.OK, (data) => {
          if (data) {
            Utils.emit(channelEvent.current, EventUtils.RefreshOrder, true)
            setTimeout(() => {
              getOrderInfo();
            }, 1000)
          }
        })
      } else if (type === 2) {
        Utils.modal("提示", "确定要取消吗？", true, (ok) => {
          if (ok) {
            orderCancelApi(orderInfo.current?.id).then((r) => {
              if (r) {
                Utils.emit(channelEvent.current, EventUtils.RefreshOrder, true)
                Utils.showOkToast("取消成功")
                setTimeout(() => {
                  getOrderInfo();
                }, 1000)
              }
            })
          }
        })
      } else if (type === 3) {
        const params: InvoiceParams = {
          type: 2,
          item: orderInfo.current
        }
        Utils.navigateAndListenToEvent(Utils.getUrlWithObject(RouthPath.applyRecharge, params), EventUtils.OK, (data) => {
          if (data) {
            setTimeout(() => {
              getOrderInfo();
            }, 1000)
          }
        })
      } else if (type === 4) {
        const params: IdParams = {
          id: orderInfo.current?.reports ?? ''
        }
        Utils.navigateTo(
          {
            url: Utils.getUrlWithObject(RouthPath.testResult, params),
          }
        )
      }
    }
  }, [getOrderInfo]);
  const [show, setShow] = useState(false)

  const getWayOrRecycleText = useCallback((id, type) => {
    if (id == null || type == null) {
      return '';
    }
    if (type === 0) {
      return LocalData.way[id].text
    } else if (type === 1) {
      return LocalData.recycle[id].text
    } else {
      return LocalData.way2[id].text
    }
  }, []);
  const renderBottomButtons = useCallback(() => {
    let bottomButtons = null;
    if (orderInfo.current) {
      let cancelButton = (
        // <Button style={{marginLeft: '10px', top: '10px'}} size='normal' type='info' hairline plain onClick={(e) => {
        //   handleButtons(2);
        // }}
        // >
        //   取消
        // </Button>
        <View></View>
      )
      let reportsButton = (
        <Button style={{marginLeft: '10px', top: '24px'}} size='normal' type='info' onClick={(e) => {
          handleButtons(4);
        }}
        >
          查看检测报告
        </Button>
      )
      //待支付，待确认
      if (orderInfo.current?.status === OrderStatus.WAIT_PAYMENT || orderInfo.current?.status === OrderStatus.WAIT_CONFIRMATION) {
        //要显示个人支付还是团队支付
        const isPay = orderInfo.current?.status === OrderStatus.WAIT_PAYMENT;
        const btnText = isPay ? '去支付' : '去确认';
        bottomButtons = (
          <View style={{display: 'flex', flexDirection: 'row'}}>
            {cancelButton}
            <View style={{flex: 1}}>
              <BottomButton submitText={btnText} onSubmit={() => {
                handleButtons(isPay ? 0 : 1);
              }} margin='10px 24px 24px 24px'
              />
            </View>
          </View>
        )
      } else if (orderInfo.current?.status < OrderStatus.FINISHED) {
        bottomButtons = (
          <View style={{display: 'flex', flexDirection: 'row',}}>
            {/*<Button style={{flex: 1, margin: '24px'}} size='normal' type='info' hairline plain onClick={(e) => {*/}
            {/*  handleButtons(2);*/}
            {/*}}*/}
            {/*>*/}
            {/*  取消*/}
            {/*</Button>*/}
          </View>
        )
      } else if (orderInfo.current?.status === OrderStatus.FINISHED) {
        if (orderInfo.current?.payWay === 2) {
          bottomButtons = (
            <View style={{display: 'flex', flexDirection: 'row',}}>
              {
                orderInfo.current?.reports ? reportsButton : null
              }
              <Button style={{flex: 1, margin: '24px'}} size='normal' type='info' hairline plain onClick={(e) => {
                handleButtons(3);
              }}
              >
                申请发票
              </Button>
            </View>
          )
        } else {
          bottomButtons = (
            <View>
              {
                orderInfo.current?.reports ? <View style={{display: 'flex', flexDirection: 'row',}}>
                  <Button style={{flex: 1, margin: '24px'}} size='normal' type='info' onClick={(e) => {
                    handleButtons(4);
                  }}
                  >
                    查看检测结果
                  </Button>
                </View> : null
              }
            </View>
          )
        }
      }
    }
    return (
      <View>
        {bottomButtons}
      </View>
    )
  }, []);


  const renderTimeOrNum = useCallback(() => {
    const machineType = orderInfo.current?.machineType;
    if (machineType === LocalData.notTimeId) {
      return (
        <Cell renderIcon='样品数量' renderTitle={<Text
          className='titleStyle'
          style={{
            color: 'black',
            display: 'inline-block',
            width: '100%',
            marginLeft: '10px'
          }}
        >{orderInfo.current?.bookTotalTime}</Text>}
        />
      )
    } else {
      return (
        <View>
          <Cell renderIcon={`预约时间(${DateUtils.getHours(orderInfo.current?.bookAllTimes)}h)`}/>
          <View className='gridLayout100_2'>
            {
              DateUtils.formatAndMergeDateTimeRanges(orderInfo.current?.bookAllTimes).map((time, index) => {
                return (
                  <View key={index} className='gridItem'>
                    <Text>{time.date}</Text>
                    <Text>{time.time}</Text>
                  </View>
                )
              })
            }
          </View>
        </View>
      )
    }
  }, []);


  const renderProject2 = useCallback(() => {
    const appendixOneName = orderInfo.current?.appendixOneName
    return (
      <View>
        {
          appendixOneName ? (<Cell renderIcon={appendixOneName}
                                   renderTitle={<Text
                                     style={{color: 'red', paddingLeft: '10px', fontSize: '14px',}}
                                   >{ShowUtils.getDefaultPrice(NumberUtils.multiplyStrings(orderInfo.current?.appendixOnePrice, orderInfo.current?.appendixOneNum))}</Text>}
          />) : null
        }
      </View>
    )
  }, []);


  const renderShippingAddressCell = useCallback(() => {
    const way = orderInfo.current?.way;
    const addressMap = {
      '0': {
        icon: '取样地址',
        text: orderInfo.current?.wayDetail,
      },
      '1': {
        icon: '邮寄地址',
        text: LocalData.acceptAddress,
      },
    };

    const config = addressMap[way];
    if (!config) return null;

    const handleCopy = () => {
      Utils.copyToClipboardText(config.text);
    };

    return (
      <Cell
        renderIcon={config.icon}
        renderTitle={<Text
          className='titleStyle'
          style={{
            color: 'black',
            display: 'inline-block',
            marginRight: '20px',
            marginLeft: '20px'
          }}
        >{config.text}</Text>}
        renderExtra={<Image src={AssetImage.copy as string} style={{
          width: '24px',
          height: '24px'
        }}
        />}
        onClick={handleCopy}
      />
    );
  }, [orderInfo.current?.way, orderInfo.current?.wayDetail, LocalData.acceptAddress]);


  const renderMoreOptons = useCallback(() => {
    return (
      <View>
        {Utils.isEmptyJsonObject(orderInfo.current?.otherIdJson) ? null :
          <Cell renderTitle='更多选项' isLink onClick={() => {
            const result = Utils.restoreKeys(JSON.parse(orderInfo.current?.otherIdJson || '{}'))
            const moreOptionsWithProjectId = {
              ...result,
              id: orderInfo.current?.projectId
            };
            const url = Utils.getUrlWithObject(RouthPath.projectBookMore, moreOptionsWithProjectId)
            Utils.navigateTo({
              url
            })
          }}
          />}
      </View>
    )
  }, []);
  return (
    <View>
      {
        orderInfo.current ?
          <View style={{height: '100vh', boxSizing: 'border-box', display: 'flex', flexDirection: 'column'}}>
            <View style={{boxSizing: 'border-box', flex: 1, position: 'relative', overflow: 'hidden'}}>
              <ScrollView scrollY
                          style={{boxSizing: 'border-box', height: '100%'}}
              >
                <View>
                  <Cell
                    renderTitle={<View
                      style={{display: 'flex', justifyContent: 'space-between'}}
                    ><View><Text>订单号</Text><Text
                      style={{color: 'black'}}
                    >{`(${orderInfo.current?.id})`}</Text></View>{
                      statusStyle.current ? <Text
                        style={{color: statusStyle.current?.color}}
                      >{statusStyle.current?.text}</Text> : <View></View>
                    }</View>}
                  />
                  <CellGroup
                    title={<View style={{
                      display: 'flex',
                      flexDirection: 'row',
                      justifyContent: 'space-between',
                    }}
                    ><Text>项目信息</Text> <View onClick={() => {
                      openDialog()
                    }}
                    ><Icon name='service' color='#517be9'/><Text
                      style={{color: '#517be9'}}
                    >客服</Text></View></View>}
                  >
                    <Cell renderIcon='机器'
                          renderTitle={<Text
                            className='titleStyle'
                            style={{
                              color: 'black',
                              display: 'inline-block',
                              width: '100%',
                              marginLeft: '10px'
                            }}
                          >{orderInfo.current?.machineName}</Text>}
                    />
                    <Cell renderIcon='项目'
                          renderTitle={<View style={{display: 'flex', alignItems: 'center', flexDirection: 'row'}}>
                            <View style={{marginLeft: '10px'}}>
                              <Image
                                src={ShowUtils.getImageUrl(ShowUtils.getDefault(orderInfo.current?.projectImage, ''))}
                                style={{width: '50px', height: '50px'}} fit='cover'
                              />
                            </View>
                            <Text
                              className='titleStyle'
                              style={{
                                color: 'black',
                                display: 'inline-block',
                                width: '100%',
                                marginLeft: '20px'
                              }}
                            >{orderInfo.current?.projectName}</Text></View>}
                    />
                    {
                      renderTimeOrNum()
                    }
                    {
                      renderProject2()
                    }
                    <Cell renderIcon='价格'
                          renderTitle={<View style={{
                            marginLeft: '10px',
                            flex: 1,
                            display: 'flex',
                            flexDirection: 'row',
                            justifyContent: 'flex-start',
                            alignItems: 'center'
                          }}
                          >
                            <Text style={{
                              fontSize: '16px',
                              color: 'red',
                            }}
                            >{ShowUtils.getDefaultPrice(orderInfo.current?.actualAmount)}</Text>
                            <Text style={{
                              fontSize: '14px',
                              color: 'gray',
                              textDecoration: 'line-through',
                            }}
                            >{`(${ShowUtils.getDefaultPrice(orderInfo.current?.amount)})`}</Text>
                            {
                              orderInfo.current?.couponsDiscount ? <Text style={{
                                fontSize: '14px',
                                color: 'gray',
                              }}
                              >{`已使用${ShowUtils.getDefaultPrice(orderInfo.current?.couponsDiscount)}优惠券`}</Text> : null
                            }
                          </View>}
                    />

                  </CellGroup>
                  <CellGroup title={<Text>用户信息</Text>}>
                    <Cell renderIcon='联系人姓名' renderTitle={<Text
                      className='titleStyle'
                      style={{
                        color: 'black',
                        display: 'inline-block',
                        width: '100%',
                        marginLeft: '20px'
                      }}
                    >{orderInfo.current?.contacts}</Text>}
                    />
                    <Cell renderIcon='联系人电话' renderTitle={<Text
                      className='titleStyle'
                      style={{
                        color: 'black',
                        display: 'inline-block',
                        width: '100%',
                        marginLeft: '20px'
                      }}
                    >{orderInfo.current?.phone}</Text>}
                    />
                    {
                      ShowUtils.isValidTeamId(orderInfo.current?.teamId) ?
                        <Cell renderIcon='团队名称' renderTitle={<Text
                          className='titleStyle'
                          style={{
                            color: 'black',
                            display: 'inline-block',
                            width: '100%',
                            marginLeft: '20px'
                          }}
                        >{orderInfo.current?.teamName}</Text>}
                        /> : null
                    }
                    {
                      Utils.isNotBlank(orderInfo.current?.email) ?
                        <Cell renderIcon='邮箱地址'
                              renderExtra={<Image src={AssetImage.copy as string} style={{
                                width: '24px',
                                height: '24px'
                              }}
                              />}
                              onClick={() => {
                                Utils.copyToClipboardText(`${orderInfo.current?.email}`)
                              }}

                              renderTitle={<Text
                                className='titleStyle'
                                style={{
                                  color: 'black',
                                  display: 'inline-block',
                                  width: '100%',
                                  marginLeft: '20px'
                                }}
                              >{orderInfo.current?.email}</Text>}
                        /> : null
                    }
                  </CellGroup>

                  <CellGroup title='样品信息'>

                    <Cell renderIcon='拍摄方式' renderTitle={<Text
                      className='titleStyle'
                      style={{
                        color: 'black',
                        display: 'inline-block',
                        width: '100%',
                        marginLeft: '20px'
                      }}
                    >{
                      getWayOrRecycleText(orderInfo.current?.shootingWay, 2)
                    }</Text>}
                    />
                    <Cell renderIcon='取样方式' renderTitle={<Text
                      className='titleStyle'
                      style={{
                        color: 'black',
                        display: 'inline-block',
                        width: '100%',
                        marginLeft: '20px'
                      }}
                    >{
                      getWayOrRecycleText(orderInfo.current?.way, 0)
                    }</Text>}
                    />
                    {
                      renderShippingAddressCell()
                    }
                    <Cell renderIcon='样品是否回收' renderTitle={<Text
                      className='titleStyle'
                      style={{
                        color: 'black',
                        display: 'inline-block',
                        width: '100%',
                        marginLeft: '20px'
                      }}
                    >{
                      getWayOrRecycleText(orderInfo.current?.recycle, 1)
                    }</Text>}
                    />
                    {
                      orderInfo.current?.recycle === 0 ? <Cell renderIcon='回收地址' renderTitle={<Text
                        className='titleStyle'
                        style={{
                          color: 'black',
                          display: 'inline-block',
                          marginRight: '20px',
                          marginLeft: '20px'
                        }}
                      >{orderInfo.current?.recycleDetail}</Text>}
                      /> : null
                    }
                    <Cell renderIcon='备注' renderTitle={<Text
                      className='titleStyle'
                      style={{
                        color: 'black',
                        display: 'inline-block',
                        width: '100%',
                        boxSizing: 'border-box',
                        paddingLeft: '20px',
                        paddingRight: '10px',
                      }}
                    >{ShowUtils.getDefault(orderInfo.current?.note, '无')}</Text>}
                    />
                  </CellGroup>
                  {
                    NumberUtils.isActuallyNumber(orderInfo.current?.payWay) && orderInfo.current?.status === OrderStatus.FINISHED ?
                      <Cell renderIcon={<Text style={{marginRight: '10px'}}>支付方式</Text>}
                            title={ShowUtils.getPayWay(orderInfo.current?.payWay)}
                      /> : null
                  }
                  {
                    renderMoreOptons()
                  }
                </View>
              </ScrollView>
            </View>
            {
              idParams.current?.isHideButton ? null : renderBottomButtons()
            }
          </View> : <View>
            <Empty description='暂无数据'/>
          </View>
      }
      <ActionSheet
        show={show}
        cancelText='取消'
        title='请选择支付方式'
        actions={options.current}
        onCancel={() => setShow(false)}
        onClose={() => setShow(false)}
        onSelect={(e) => handlePayStyleSelect(e)}
      />
      <KefuDialog ref={kefuDialogRef}/>
    </View>
  )
}
